import Taro, { Component } from '@tarojs/taro'
import {
  Swiper,
  SwiperItem,
  Image,
  View,
  Text,
  Input,
} from '@tarojs/components'
import '../../assets/common.scss'
import CommonJs from '../../utils/common'
import Footer from '../index/footer'
import Gwlist from '../index/gwlist'
import './mall.scss'

import cat01 from './images/pcat01.png'
import cat02 from './images/pcat02.png'
import cat03 from './images/pcat03.png'
import cat04 from './images/pcat04.png'
import cat05 from './images/cat05.png'
import cat06 from './images/cat06.png'
import cat07 from './images/cat07.png'
import cat08 from './images/cat08.png'
import notice from './images/notice.png'
import mall01 from './images/mall01.jpg'
import mall02 from './images/mall02.jpg'
import mall03 from './images/mall03.jpg'
import ban01 from './images/ban01.png'
import ban02 from './images/ban02.png'
import searchimg from './images/search.png'

import foot03 from '../../assets/kedouimg01/foot07.png'
import foot04 from '../../assets/kedouimg01/foot4.png'
import foot05 from '../../assets/kedouimg01/foot09.png'

export default class Index extends Component {
  constructor(props) {
    super(props)
    this.state = {
        noticelist:[],
        goodslist:[],
        gglist:[],
        name:'',
        iszb:'',
        navwidth:0,
        flindex:0,
        goodscat:[],
	   		pageheight:0,//获取高度
	   		pageNumber:1,//页码数
       scrollPd:false,//是否可滑动
       hasNextPage:false,//是否有下一页
     appmark:CommonJs.getmark(),
     webname:CommonJs.getname(),
     isIphoneX:0,
    }
  }
  config = {
    navigationBarTitleText: '加载中',
  }
  dobt(){
	if(this.state.appmark=='xjzb'){
		Taro.setNavigationBarTitle({title:'WGM商城'})
	}
	else{
		Taro.setNavigationBarTitle({title:this.state.webname+'商城'})
	}
  }
  open(url, type) {
    if (Taro.getEnv() === Taro.ENV_TYPE.WEAPP) {
      this.$preload({
        type: type,
      })
    } else if (Taro.getEnv() === Taro.ENV_TYPE.WEB) {
      url = url + '?type=' + type
    }

    CommonJs.openTo(url)
  }
  openhd(url) {
    var dateinfo = Taro.getStorageSync('dateinfo')
    var curl = url + '?scene=' + dateinfo.qid
    CommonJs.openTo(curl)
  }

  componentWillMount () {
  	this.dobt()
  	
	var par =this.$router.params
	var _this=this;
	if(par){
		var cs=par.scene;
		var vs=par.query_id;
		if(vs&&vs.indexOf('goodsxq')>=0){
			cs=vs
		}
		if(cs&&cs.indexOf('goodsxq')>=0){
			var arr=cs.split("goodsxq");
			var obj={};
			obj.qid=arr[0];
			var date1={ 
			  clusterId:arr[0]
			}
			CommonJs.ajaxRequest('/openClusterBindingUser/create',date1,'GET',function(res){},'noloading')
			if(arr.length>2){
				Taro.setStorage({key:'dateinfo',data:obj})
				Taro.setStorage({key:'shopId',data:arr[1]})
				Taro.setStorage({key:'goodsid',data:arr[2]})
				this.open('/pages/mall/goodsxq',arr[2])
			}
			else{
				Taro.setStorage({key:'dateinfo',data:obj})
				Taro.setStorage({key:'goodsid',data:arr[1]})
				if(arr[1]){
					var url='/mall/papi/v1.9/item/'+arr[1]
					
					CommonJs.ajaxRequest(url,'','GET',function(res){
						Taro.setStorage({key:'shopId',data:res.data.shop.shopId})
						_this.open('/pages/mall/goodsxq',arr[1])
					})
				}
			}
		}
		else if(cs&&cs.indexOf('goodstg')>=0){
			var arr=cs.split("goodstg");
			var obj={};
			obj.qid=arr[0];
			Taro.setStorage({key:'dateinfo',data:obj})
			Taro.setStorage({key:'goodsid',data:arr[1]})
			this.setsharcode(arr[1],arr[2])
			var url='/mall/papi/v1.9/item/'+arr[1]
			CommonJs.ajaxRequest(url,'','GET',function(res){
				Taro.setStorage({key:'shopId',data:res.data.shop.shopId})
				_this.open('/pages/mall/goodsxq',arr[1])
			})
		}
	}
		var webinfo=Taro.getStorageSync('webinfo')
    this.setState({
      iszb:webinfo.iszb
    })
    this.getQunName();
    this.getnotice();
    this.getgg();
    this.getcat();
    
    
    var navwidths = Taro.getStorageSync('navwidths')
    if (navwidths != '' || navwidths != 'undefined') {
      if (navwidths == 1) {
        Taro.getSystemInfo({
          success:function(res){
            var windowWidth = res.windowWidth
            var navwidth = windowWidth / 6
            _this.setState({
              navwidth:navwidth
            })
          }
        })
      }
    }
    const app = Taro.getApp();
  	let isIphoneX = app.globalData.isIphoneX;
  	
  	this.setState({
     	isIphoneX:isIphoneX
   })
  }


  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

   getQunName(){
		var dateinfo = Taro.getStorageSync('dateinfo')
    var date1={id:dateinfo.qid}
		var _this=this;
		var wh=0;
		Taro.getSystemInfo({
		  success:function(res){
			wh=res.windowHeight;
		  }
		})
		var query=Taro.createSelectorQuery()
		query.select('.mypage').boundingClientRect(function(rect){
		  _this.setState({
			  pageheight:wh-rect.height
		  })
		}).exec();
	   
  }
  settginfo(goodsid,code){
  	/*设置缓存推广码5分钟*/
  	var obj={}
		obj.goodsid=goodsid;
		obj.tgcode=201;
  }
  getnotice() {
    var shopId = Taro.getStorageSync('shopId')
    var url = '/advert/papi/v1.9/notice/obtain/' + shopId
    var _this = this
    CommonJs.ajaxRequest(url, '', 'GET', function(res) {
      _this.setState({
        noticelist: res.data,
      })
    })
  }
  getgg() {
    var shopId = Taro.getStorageSync('shopId')
    var url = '/advert/papi/v1.9/advert/type/5/' + shopId
    var _this = this
    CommonJs.ajaxRequest(url, '', 'GET', function(res) {
      var arr = res.data
      if (arr.length == 0) {
        var obj = {}
        obj.picUrl = ban02
        obj.targetType = 2
        arr[0] = obj
      }
      _this.setState({
        gglist: arr,
      })
    })
  }
  gggoto(type, id) {
    if (type == 3) {
      this.open('/pages/mall/goodscat', id.toString())
    } else if (type == 5) {
      this.open('/pages/mall/goodsxq', id.toString())
    } else {
    }
  }

  getInputVal(event) {
    var m = event.target
    var obj = {}
    obj[m.id] = m.value
    this.setState(obj)
  }
  search() {
    this.open('/pages/mall/goodslist', 'search')
  }
  goodsxq(index) {
  	var goodsid=this.state.goodslist[index].id
  	Taro.setStorage({key:'goodsid',data:goodsid})
    this.open('/pages/mall/goodsxq', this.state.goodslist[index].id)
  }
  setsharcode(goodsid,code){
  	/*设置商品分享码，5分钟后失效*/
  	var arr=Taro.getStorageSync('shareCode');
  	if(!arr){
  		arr=[]
  	}
  	var obj={};
  	obj.sharcode=code;
  	obj.goodsid=goodsid;
  	obj.time= Date.parse(new Date())/1000
  	arr.push(obj)
  	Taro.setStorage({key:'shareCode',data:arr})
  }
  
  
  getcat(){
	var shopId = Taro.getStorageSync('shopId')
    var url='/commodity/papi/v2.0/item-groups/'+shopId
    var _this=this;
    CommonJs.ajaxRequest(url,'','GET',function(res){
       _this.setState({
        goodscat: res.data
      })
      if(res.data.length>0){
        var type=_this.$router.preload.type;
        if(!type.type){
          for(var i=0;i<res.data.length;i++){
            if(type==res.data[i].id){
              _this.setState({
                flindex:i
              })
            }
          }
           _this.getGoodsByCatid(0,type)
        }
        else{

          _this.getGoodsByCatid(0,res.data[0].id)
        }
      }
    })
  }
  choosefl(index){
    this.setState({
      flindex:index,
      goodslist:[]
      })
    this.getGoodsByCatid(0,this.state.goodscat[index].id)
  }
  getGoodsByCatid(pageNumber,id){
	var url='/mall/papi/v1.9/item?itemGroupId='+id+'&page='+pageNumber+'&activeStatus=ENABLE'
	var _this=this;
    CommonJs.ajaxRequest(url,'','GET',function(res){

		 if(res.data.page<res.data.totalPages){
			var hasNextPage = true
		 }
		 else{
			var hasNextPage = false
		 }
          var results = _this.state.goodslist
          var result = res.data.list;
          for(var i = 0; i < result.length; i++){
            results.push(result[i])
          }
          if (hasNextPage) {
            _this.setState({
              goodslist:results,
              pageNumber: res.data.page,
              hasNextPage: hasNextPage,
              scrollPd: true
            })
          }
		  else {
            _this.setState({
              goodslist:results,
              pageNumber: res.data.page,
              hasNextPage: hasNextPage,
              scrollPd: false
            })
          }

    })
  }
  loadMore(){
    var _this = this;
    var pd = _this.state.scrollPd;
    if(pd) {
      //防止多次触发滑动到底部事件
      _this.setState({
        scrollPd: false//禁止下拉
      })
      var pageNumber = _this.state.pageNumber + 1;
	  var cindex=_this.state.flindex;
	  var goodscat=_this.state.goodscat;
      _this.getGoodsByCatid(pageNumber,goodscat[cindex].id);
    }else{
      var hasNextPage =  _this.state.hasNextPage;
      if(hasNextPage){
        Taro.showToast({
            title:'正在加载数据...',
            icon: 'none',
            duration: 2000
          });
      }else{
        Taro.showToast({
            title:'没有更多数据啦！',
            icon: 'none',
            duration: 2000
          });
      }
    }
  }
  
  goopen(type,url){
	  this.$preload({
	    malltype:type
	  })
    CommonJs.openTo(url)
  }
  
  render() {
    const goodslist = this.state.goodslist
    const noticelist = this.state.noticelist
    const gglist = this.state.gglist
    const goodscat= this.state.goodscat;
    return (
      <View className='page footpage'>
      <ScrollView className='mypage' scrollY='true' style='height:100%;background-color:#fff;' onScrollToLower={this.loadMore.bind(this,'')}>
        <View className='mallPage'>
			<View className='focusImg'>
				<Swiper
				className="swiper-container"
				autoplay>
         {gglist.map((item, index) => (
				 <SwiperItem onClick={this.gggoto.bind(this,item.targetType,item.targetId)}>
				   <Image className="swiper-img" mode="widthFix" src={item.picUrl}></Image>
				 </SwiperItem>
         ))}
			  </Swiper>
			</View>
			
			<View className='index-focus' style="margin-top:100px">
				<View className='index-focus-left' onClick={this.open.bind(this,'/pages/mall/goodslist','saleAmountSort')}>
					<Image className="focus-left-img" mode="widthFix" src={mall01}></Image>
					<Text className='pt'>热门榜单</Text>
					<Text className='ptinfo'>根据销量搜索等综合得出</Text>
		      	</View>
		      	<View className='index-focus-right'>
		      		<View className='index-focus-right01' onClick={this.open.bind(this,'/pages/mall/goodslist','createAt')}>
						<Image className="focus-left-img" mode="widthFix" src={mall02}></Image>
			      		<Text className='pt'>首发新品</Text>
			      		<Text className='ptinfo'>多个优质商品最新上架</Text>
			      	</View>
			      	<View className='index-focus-right02' onClick={this.open.bind(this,'/pages/mall/goodslist','cx')}>
						<Image className="focus-left-img" mode="widthFix" src={mall03}></Image>
			      		<Text className='pt'>促销专区</Text>
			      		<Text className='ptinfo'>火热销售中</Text>
			      	</View>
		      	</View>
		    </View>
			<View className='tj-goods' style='padding-bottom:60rpx;'>
				<View className='tit catfl'>
					<ScrollView 
              className='qun-fung' 
              scrollX='true'
              scrollLeft={this.state.navwidth}>
								{goodscat.length>0&&goodscat.map((item, index) => (
									<Text className={index==this.state.flindex?'tit01 tit02':'tit01'} onClick={this.choosefl.bind(this,index)}>{item.groupName}</Text>
								))}
								
					</ScrollView>
				</View>
				<View className='tj-goods-box'  style={goodslist.length>0?'display:block;padding-bottom:110rpx':'display:none;'}>
					
					{goodslist.map((item, index) => (
					<View className='goods-li' onClick={this.goodsxq.bind(this,index)}>
						<View className='cat-li-img'>
							<Image className='goods-logo' mode='scaleToFill' src={item.logoUrl?item.logoUrl:'https://minichat.g2ma.com/kedouimg/A6984900727459logo.png'}></Image>
						</View>
						<View className='sp-info'>
							<Text className='sp-name'>{item.name}</Text>
							<View className='sp-price'>￥{item.price.specialPrice/100}</View>
							<Text className='sp-kc'>剩余：{item.saleStock.stockAmount}件</Text>
							<Text className='sp-rcprice'>日常1价：￥{item.price.marketPrice?item.price.marketPrice/100:item.price.specialPrice*1.5/100}</Text>
						</View>
					</View>
					
					))}
					
				</View>
				
				<View className='tj-goods-box' style={goodslist.length>0?'display:none':'display:block;'}>
					<View className="nodate">暂无推荐商品，敬请期待</View>
				</View>
			</View>
			
		</View>
		<Gwlist></Gwlist>
			<View className='footer' style={this.state.isIphoneX==1?'padding-bottom:58rpx;display:flex;':'display:flex;'}>
					<View className='footer-dl' onClick={this.goopen.bind(this,'','/pages/mall/shopcar')}>
						<View className='footer-dt'>
							<Image className='footer-img' mode='widthFix' src={foot04}></Image>
						</View>
						<View className='footer-dd'>购物车</View>
					</View>
					<View className='footer-dl' onClick={this.goopen.bind(this,'','/pages/my/unpaid')}>
						<View className='footer-dt'>
							<Image className='footer-img' mode='widthFix' src={foot03}></Image>
						</View>
						<View className='footer-dd'>订单</View>
					</View>
					<View className='footer-dl' onClick={this.goopen.bind(this,'','/pages/my/my')}>
						<View className='footer-dt'>
							<Image className='footer-img' mode='widthFix' src={foot05}></Image>
						</View>
						<View className='footer-dd'>我的</View>
					</View>
				</View>
				</ScrollView>
      </View>
    )
  }
}
